/**
 * HTTP客户端模块
 * 提供HTTP请求功能
 */
export class HttpClient {
  constructor(ruleName) {
    this.ruleName = ruleName;
    this.defaultHeaders = {
      'User-Agent': 'NetworkFirewall/1.0'
    };
  }

  // GET请求
  async get(url, options = {}) {
    return this.request(url, { ...options, method: 'GET' });
  }

  // POST请求
  async post(url, data, options = {}) {
    return this.request(url, {
      ...options,
      method: 'POST',
      body: typeof data === 'string' ? data : JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      }
    });
  }

  // PUT请求
  async put(url, data, options = {}) {
    return this.request(url, {
      ...options,
      method: 'PUT',
      body: typeof data === 'string' ? data : JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      }
    });
  }

  // DELETE请求
  async delete(url, options = {}) {
    return this.request(url, { ...options, method: 'DELETE' });
  }

  // PATCH请求
  async patch(url, data, options = {}) {
    return this.request(url, {
      ...options,
      method: 'PATCH',
      body: typeof data === 'string' ? data : JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      }
    });
  }

  // 通用请求方法
  async request(url, options = {}) {
    try {
      const method = options.method || 'GET';
      console.log(`🌐 ${this.ruleName}: HTTP ${method} ${url}`);
      
      const response = await fetch(url, {
        headers: {
          ...this.defaultHeaders,
          ...options.headers
        },
        ...options
      });
      
      const result = {
        status: response.status,
        statusText: response.statusText,
        headers: Object.fromEntries(response.headers.entries()),
        ok: response.ok,
        url: response.url,
        text: async () => await response.text(),
        json: async () => await response.json(),
        blob: async () => await response.blob(),
        arrayBuffer: async () => await response.arrayBuffer()
      };
      
      console.log(`🌐 ${this.ruleName}: HTTP ${method} ${url} -> ${response.status}`);
      return result;
    } catch (error) {
      console.error(`🌐 ${this.ruleName}: HTTP ${options.method || 'GET'} ${url} failed:`, error);
      throw error;
    }
  }
} 